package com.jielin.handling.third.xsky.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.MultipartUpload;
import com.amazonaws.services.s3.model.MultipartUploadListing;
import com.amazonaws.services.s3.model.PartETag;
import com.amazonaws.services.s3.model.PartListing;
import com.amazonaws.services.s3.model.PartSummary;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.jielin.handling.third.xsky.XskyS3Basic;
import com.jielin.handling.third.xsky.XskyS3Bucket;
import com.jielin.handling.third.xsky.XskyS3Object;

public class XskyS3Demo 
{
    private static String bucketName = null;
    private static String MultipartUploadFile = null;
    private static String UploadFile = null;
    private static String endpoint = "10.252.90.20";
    public XskyS3Basic basic = null;
    public XskyS3Bucket S3Bucket = null;
    public XskyS3Object S3Object = null;
    
    public static void main(String[] args) 
    {
		getConf(args[0]);
		XskyS3Demo demo = new XskyS3Demo();
		demo.show();
    }
    
    public void show() {
    	String uploadIdforlistParts = null;
        try {	
            // 创建桶
            if (!S3Bucket.HasBucket(bucketName)) {
            	S3Bucket.CreatingBucket(bucketName);
                System.out.println("Successful create bucket: " + bucketName + "\n");
            } else {
            	S3Bucket.HeadBuckte(bucketName);
                System.out.println("Bucket " + bucketName + " is exists, No need to ceate it!\n");
            }
            
            // 获取桶列表
            List<Bucket> buckets = S3Bucket.ListBuckets();
            System.out.println("All buckets as below:");
            for (Bucket bucket : buckets) {
            	System.out.println("  " + bucket.getName());
            	System.out.println();
            }
            
            // 整体上传
            System.out.println(new Date().toString());
            System.out.println("Begin to put object \"" + UploadFile + "\" by putObject.");
            File file1 = new File(UploadFile);
            S3Object.PutObject(bucketName, UploadFile, file1);
            System.out.println("Successful put object \"" + UploadFile + "\" by putObject.\n");
            System.out.println(new Date().toString());
            
            // 分段上传
            System.out.println("Begin to put object \"" + MultipartUploadFile + "\" by MultipartUpload.");
            File file2 = new File(MultipartUploadFile);
            List<PartETag> partETags=new ArrayList<PartETag>();
            uploadIdforlistParts = S3Object.multiPutObject(bucketName, MultipartUploadFile, file2, partETags);
            System.out.println("Successful put object \"" + MultipartUploadFile + "\" by MultipartUpload.\n");
            
            // 列出所有未完成的分段上传
            System.out.println("Begin list all multiupload:");
            MultipartUploadListing multiUpList = S3Bucket.listMultipartUploads(bucketName);
            for (MultipartUpload upload: multiUpList.getMultipartUploads()) {
            	System.out.println("Key:" + upload.getKey());
            	System.out.println("Owner:" + upload.getOwner().toString());
            	System.out.println("UpLoadID:" + upload.getUploadId());
            	System.out.println("Time:" + upload.getInitiated().toString() + "\n");
            }
            
            // 列出指定分段上传的Part
            System.out.println("Begin list part of \"" + MultipartUploadFile + "\":\n");
            PartListing partLists = S3Object.listParts(bucketName, MultipartUploadFile, uploadIdforlistParts);
            for(PartSummary part: partLists.getParts()) {
            	System.out.println("  Num :" + part.getPartNumber());
            	System.out.println("  ETag:" + part.getETag());
            }
            //完成分段上传
            S3Object.finish(bucketName, MultipartUploadFile, uploadIdforlistParts, partETags);
            System.out.println();
            
            // 获取对象列表
            System.out.println("List objects of bucket(" + bucketName + "): ");
            List<S3ObjectSummary> obj_list = S3Object.ListingObjects(bucketName);
            for (S3ObjectSummary obj_summary : obj_list) {
            	System.out.println("  " + obj_summary.getKey());
            }
            System.out.println();
            
            // 读取对象
            String getFile = UploadFile + "_new";
            S3Object s3object = S3Object.getObject(bucketName, UploadFile);
            System.out.println("Get object: " + UploadFile + " as " + getFile);
            XskyS3Basic.WriteNewFile(s3object.getObjectContent(), getFile); 
            s3object.close();
            // 删除对象
        	System.out.println("Begin delete objects: " + UploadFile + ", " + MultipartUploadFile + ".\n");
        	List<DeleteObjectsRequest.KeyVersion> listKeys = new ArrayList<DeleteObjectsRequest.KeyVersion>();
        	listKeys.add(new DeleteObjectsRequest.KeyVersion(UploadFile));
        	listKeys.add(new DeleteObjectsRequest.KeyVersion(MultipartUploadFile));
        	S3Object.deleteObjectS(bucketName, listKeys);
        	
            // 删除桶
        	System.out.println("Begin delete bucket: " + bucketName + ".\n");
        	S3Bucket.DeletingBucket(bucketName);      	
        	System.out.println("Finish!"); 
        	
        }  catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which" + " means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which means" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }catch (IllegalArgumentException  e) {
        	System.out.println("Caught an IllegalArgumentException, Maybe you input a wrong argument.");
        	System.out.println("Error Message:	" + e.getMessage());	
        }catch (IOException e) {
        	System.out.println("Error Message:	" + e.getMessage());	
        }
    }
    
    public XskyS3Demo() {
    	// 创建连接
    	basic = new XskyS3Basic(endpoint);
        S3Bucket = new XskyS3Bucket(basic.client);
        S3Object = new XskyS3Object(basic.client);
    }

    public static void getConf(String fileName) {
    	try {
    		FileReader reader = new FileReader(fileName);
			BufferedReader br = new BufferedReader(reader);
            String str = null;                      
            while((str = br.readLine()) != null) {                               
            	String[] conf = str.split("=", 2);
            	if(conf[0].trim().compareTo("Endpoint") == 0)
            		endpoint = conf[1].trim();
            	if(conf[0].trim().compareTo("BucketName") == 0)
            		bucketName = conf[1].trim();
            	if(conf[0].trim().compareTo("MultipartUploadFile") == 0)
            		MultipartUploadFile = conf[1].trim();
            	if(conf[0].trim().compareTo("UploadFile") == 0)
            		UploadFile = conf[1].trim();
            }
            reader.close();
            br.close();
        } catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}catch(IOException e) {
            e.printStackTrace();
            System.exit(1);
      }
    }

}